﻿using AutoMapper;
using BackData;
using Details.API.Application.Command.Goods;
using Dm;
using Domain;
using Infratructure.RepositoryWay;
using MediatR;

namespace Details.API.Application.Handler.Goods
{
    public class UpdateGoodsHandler : IRequestHandler<UpdateGoodsCommand, APIResult<int>>
    {
        private readonly IRepository<GoodsModel> goodway;
        private readonly ILogger<AddGoodsHandler> log;
        private readonly IMapper mapper;


        public UpdateGoodsHandler(IRepository<GoodsModel> goodway, ILogger<AddGoodsHandler> log, IMapper mapper)
        {
            this.goodway = goodway;
            this.log = log;
            this.mapper = mapper;
        }

        /// <summary>
        /// 修改商品
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<int>> Handle(UpdateGoodsCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<int>();
            var value = mapper.Map<GoodsModel>(request);
            var result = await goodway.UpdateAsync(value);
            if (result <= 0)
            {
                log.LogError($"修改商品失败");
                res.Code = StateCode.Fail;
                res.Message = "修改失败";
            }
            else
            {
                log.LogInformation($"修改商品成功");
                res.Code = StateCode.OK;
                res.Message = "修改成功";
                res.Data = result;
            }
            return res;
        }
    }
}
